package com.woniu.controller.config.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.woniu.model.gh.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${jwt.signature}")
    private String signature;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String authorization = request.getHeader("Authorization");
        //是否为空
        if (!StringUtils.hasLength(authorization)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//401
            return false;
        }

        // 去除前缀前端：config.headers.Authorization = "Bearer " + token;
        authorization = authorization.replace("Bearer ", "");
        //检验令牌是否合法
        if (!JWTUtil.verify(authorization,signature.getBytes())){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//401
            return false;
        }

        //解析IP地址,发送HTTP请求的服务器IP地址进行比对
        JWT jwt = JWTUtil.parseToken(authorization);
        String requestIp = (String) jwt.getPayload("requestIp");//令牌内部的IP地址

        // 获取当前来访者的ip
        String httpIp = TokenUtil.getRequestIP(request);
        if (!requestIp.equals(httpIp)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//401
            return false;
        }

        // 判断令牌的过期时间是否超过当前时间，如果超过：令牌过期
        String exp = (String) jwt.getPayload("exp");
        LocalDateTime expTime = LocalDateTime.parse(exp, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        if(expTime.isBefore(LocalDateTime.now())){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//401
            return false;
        }
        //正常放行HTTP请求
        return true;
    }
}
